package com.dj.shop.util;

import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * @Description:
 * @Author: zhaoyu
 * @CreateDate: 2018/11/9 14:58
 * @UpdateUser:
 * @UpdateDate:
 * @UpdateRemark:
 */
public class BeanUtil {


    /**
     *
     * @description
     * 对象转MAP
     * @date: 2018/11/9 14:59
     * @author: zhaoyu
     * @UpdateUser:
     * @UpdateRemark:
     * @param obj
     * @return
     */
    public static HashMap<String, Object> convertToMap(Object obj) throws Exception {

        HashMap<String, Object> map = new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();
            boolean accessFlag = fields[i].isAccessible();
            fields[i].setAccessible(true);

            Object o = fields[i].get(obj);
            if (o != null){
                map.put(varName, o.toString());
            }

            fields[i].setAccessible(accessFlag);
        }

        return map;
    }
}
